package com.lh0811.forge.dependency.basic_web.exception;

import com.lh0811.forge.dependency.basic_web.response.ResponseStatus;
import com.lh0811.forge.dependency.basic_web.response.ServerResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class CommonExceptionAdvice {


    @ResponseBody
    @ExceptionHandler(value = {CommonException.class})
    public ServerResponse commonException(CommonException e) {
        e.printStackTrace();
        log.error("通用异常", e);
        return e.getServerResponse();
    }

    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    public ServerResponse globalError(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        log.error("未捕获异常", e);
        return ServerResponse.createByError(ResponseStatus.ERROR.getCode(), "未知错误！");
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ServerResponse throwCustomException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        log.error("参数异常", e);
        return ServerResponse.createByError(ResponseStatus.ERROR.getCode(), e.getBindingResult().getFieldError().getDefaultMessage());
    }


}
